<template>
  <div>

    <n-space vertical>
      <n-space>
        <n-button type="primary" @click="initSimulation">初始化模拟系统</n-button>
        <n-button type="primary" @click="getProductData">获取产品数据</n-button>
        <n-button type="primary" @click="startSimulation">启动模拟系统</n-button>
        <n-button type="primary" @click="stopSimulation">停止模拟系统</n-button>
      </n-space>

      <!-- 内容区域 -->
      <n-space vertical style="flex: 1; border: 1px solid #ccc; padding: 10px;">
        <n-space horizontal>
          <n-tag type="default" style="width: 160px; justify-content: center;">产线1 剩余计时</n-tag>
          <n-tag type="info" style="width: 100vh;">
            <div class="timer-container">
              <div v-for="(time, index) in parseArray(productdata.production_line1_countdown)" :key="index"
                class="timer-item">
                {{ time }}
              </div>
            </div>
          </n-tag>
        </n-space>
        <n-space horizontal>
          <n-tag type="default" style="width: 160px; justify-content: center;">产线1 产品分布</n-tag>
          <n-tag type="info" style="width: 100vh;">
            <div class="timer-container">
              <div class="product-item" v-for="(product, index) in parseArray(productdata.production_line1)"
                :key="index">
                <span class="product-label">{{ product || '空' }}</span>
                <div class="color-block" :style="{ backgroundColor: getProductColor(product) }"></div>
              </div>
            </div>
          </n-tag>
        </n-space>
        <n-space horizontal>
          <n-tag type="default" style="width: 160px; justify-content: center;">产线1 完成时间</n-tag>
          <n-tag type="info" style="width: 100vh;">
            <div class="timer-container">
              <div v-for="(time, index) in parseArray(productdata.production_line1_finsh_time)" :key="index"
                class="timer-item">
                {{ time }}
              </div>
            </div>
          </n-tag>
        </n-space>
        <n-space horizontal>
          <n-tag type="default" style="width: 160px; justify-content: center;">产线2 剩余计时</n-tag>
          <n-tag type="info" style="width: 100vh;">
            <div class="timer-container">
              <div v-for="(time, index) in parseArray(productdata.production_line2_countdown)" :key="index"
                class="timer-item">
                {{ time }}
              </div>
            </div>
          </n-tag>
        </n-space>
        <n-space horizontal>
          <n-tag type="default" style="width: 160px; justify-content: center;">产线2 产品分布</n-tag>
          <n-tag type="info" style="width: 100vh;">
            <div class="timer-container">
              <div class="product-item" v-for="(product, index) in parseArray(productdata.production_line2)"
                :key="index">
                <span class="product-label">{{ product || '空' }}</span>
                <div class="color-block" :style="{ backgroundColor: getProductColor(product) }"></div>
              </div>
            </div>
          </n-tag>
        </n-space>
        <n-space horizontal>
          <n-tag type="default" style="width: 160px; justify-content: center;">产线2 完成时间</n-tag>
          <n-tag type="info" style="width: 100vh;">
            <div class="timer-container">
              <div v-for="(time, index) in parseArray(productdata.production_line2_finsh_time)" :key="index"
                class="timer-item">
                {{ time }}
              </div>
            </div>
          </n-tag>
        </n-space>
        <n-space horizontal>
          <n-tag type="default" style="width: 160px; justify-content: center;">AGV1 产品分布</n-tag>
          <n-tag type="info" style="width: 100vh;">
            <div class="timer-container">
              <div class="product-item" >
                <span class="product-label">{{'AGV' }}</span>
                <div class="color-block" ></div>
              </div>
              <div class="product-item" v-for="(product, index) in parseArray(productdata.production_AGV1)"
                :key="index">
                <span class="product-label">{{ product || '空' }}</span>
                <div class="color-block" :style="{ backgroundColor: getProductColor(product) }"></div>
              </div>
            </div>
          </n-tag>

        </n-space>
        <n-space horizontal>
          <n-tag type="default" style="width: 160px; justify-content: center;">AGV2 产品分布</n-tag>
          <n-tag type="info" style="width: 100vh;">
            <div class="timer-container">
              <div class="product-item" >
                <span class="product-label">{{'AGV' }}</span>
                <div class="color-block" ></div>
              </div>
              <div class="product-item" v-for="(product, index) in parseArray(productdata.production_AGV2)"
                :key="index">
                <span class="product-label">{{ product || '空' }}</span>
                <div class="color-block" :style="{ backgroundColor: getProductColor(product) }"></div>
              </div>
            </div>
          </n-tag>

        </n-space>
        <n-space horizontal>
          <n-tag type="default" style="width: 160px; justify-content: center;">分拣台 产品分布</n-tag>
          <n-tag type="info" style="width: 100vh;">
            <div class="timer-container">
              <div class="product-item" >
                <span class="product-label">{{'分拣台' }}</span>
                <div class="color-block" ></div>
              </div>
              <div class="product-item" v-for="(product, index) in parseArray(productdata.sorting_station)"
                :key="index">
                <span class="product-label">{{ product || '空' }}</span>
                <div class="color-block" :style="{ backgroundColor: getProductColor(product) }"></div>
              </div>
            </div>
          </n-tag>
        </n-space>
        <n-space horizontal>
          <n-tag type="default" style="width: 160px; justify-content: center;">中继站 产品分布</n-tag>
          <n-tag type="info" style="width: 100vh;">
            <div class="timer-container">
              <div class="product-item" >
                <span class="product-label">{{'中继站' }}</span>
                <div class="color-block" ></div>
              </div>
              <div class="product-item" v-for="(product, index) in parseArray(productdata.transfer_station)"
                :key="index">
                <span class="product-label">{{ product || '空' }}</span>
                <div class="color-block" :style="{ backgroundColor: getProductColor(product) }"></div>
              </div>
            </div>
          </n-tag>

        </n-space>
        <n-space horizontal>
          <n-tag type="default" style="width: 160px; justify-content: center;">分拣AGV 产品分布</n-tag>
          <n-tag type="info" style="width: 100vh;">

            <div class="timer-container">
              <div class="product-item" >
                <span class="product-label">{{'AGV' }}</span>
                <div class="color-block" ></div>
              </div>
              <div class="product-item" v-for="(product, index) in parseArray(productdata.sorting_AGV)" :key="index">
                <span class="product-label">{{ product || '空' }}</span>
                <div class="color-block" :style="{ backgroundColor: getProductColor(product) }"></div>
              </div>
            </div>
          </n-tag>

        </n-space>
        <n-space horizontal>
          <n-tag type="default" style="width: 160px; justify-content: center;">翻转台 产品分布</n-tag>
          <n-tag type="info" style="width: 100vh;">
            <div class="timer-container">
              <div class="product-item" >
                <span class="product-label">{{'翻转台' }}</span>
                <div class="color-block" ></div>
              </div>
              <div class="product-item" v-for="(product, index) in parseArray(productdata.flip_station)" :key="index">
                <span class="product-label">{{ product || '空' }}</span>
                <div class="color-block" :style="{ backgroundColor: getProductColor(product) }"></div>
              </div>
            </div>
          </n-tag>
        </n-space>
        <n-space horizontal>
          <n-tag type="default" style="width: 160px; justify-content: center;">翻转AGV 产品分布</n-tag>
          <n-tag type="info" style="width: 100vh;">
            <div class="timer-container">
              <div class="product-item" >
                <span class="product-label">{{'AGV' }}</span>
                <div class="color-block" ></div>
              </div>
              <div class="product-item" v-for="(product, index) in parseArray(productdata.flip_AGV)" :key="index">
                <span class="product-label">{{ product || '空' }}</span>
                <div class="color-block" :style="{ backgroundColor: getProductColor(product) }"></div>
              </div>
            </div>
          </n-tag>
        </n-space>
        <n-space horizontal>
          <n-tag type="default" style="width: 160px; justify-content: center;">挂丝车 产品分布</n-tag>
          <n-tag type="info" style="width: 100vh;">
            <div class="timer-container">
              <div class="product-item" >
                <span class="product-label">{{'挂丝车' }}</span>
                <div class="color-block" ></div>
              </div>
              <div class="product-item" v-for="(product, index) in parseNestedArray(productdata.drop_rack)"
                :key="index">
                <span class="product-label">{{ product || '空' }}</span>
                <div class="color-block" :style="{ backgroundColor: getProductColor(product) }"></div>
              </div>
            </div>
          </n-tag>

        </n-space>
        <n-space horizontal>
          <n-tag type="default" style="width: 160px; justify-content: center;">出库产品</n-tag>
          <div type="info" style="width: 100vh;">
            <div class="timer-container">
              <div class="product-item" v-for="(product, index) in parseArray(productdata.out_product_list)"
                :key="index">
                <span class="product-label">{{ product || '空' }}</span>
                <div class="color-block" :style="{ backgroundColor: getProductColor(product) }"></div>
              </div>
            </div>
          </div>

        </n-space>
      </n-space>
    </n-space>

  </div>
</template>

<style scoped>
.color-block {
  width: 24px;
  height: 24px;
  border-radius: 2px;
  border: 1px solid #ccc;
}

.product-item {
  position: relative;
  width: 24px;
  height: 24px;
  margin: 0 3px;
}

.product-label {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 10px;
  color: #333;
  font-weight: bold; /* 加粗显示 */
  white-space: nowrap; /* 防止标签文字换行 */
  z-index: 10; /* 确保标签在颜色块之上 */
  text-shadow: 0 0 2px rgba(255, 255, 255, 0.8);
}

.timer-container {
  display: flex; /* 启用 flex 布局 */
  flex-wrap: wrap; /* 允许换行 */
  align-items: center; /* 垂直居中对齐 */
  padding: 2px 0; /* 调整垂直间距 */
}

.timer-item {
  width: 24px;
  height: 24px;
  margin: 0 2px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f0f0;
  border: 1px solid #ccc;
  border-radius: 2px;
  font-size: 10px;
  color: #333;
}
</style>

<script setup>
import { NButton, NTag, NSpace, NTooltip } from "naive-ui";
import axios from "axios";
import { API_URLS } from '../../utils/apiConfig';
import { ref, onMounted, onUnmounted, watch } from "vue";

// 将产品代码映射到颜色
const getProductColor = (product) => {
  if (!product) return '#f1f1f1'; // 默认灰色表示空

  const colorMap = {
    'P1': '#FF6B6B', // 红色
    'P2': '#4ECDC4', // 青色
    'P3': '#45B7D1', // 蓝色
    'P4': '#96CEB4', // 浅绿色
    'P5': '#FFEAA7', // 淡黄色
    'P6': '#DDA0DD', // 紫色
    'P7': '#F08080', // 浅红色
    'P8': '#87CEFA',  // 浅蓝色
  };

  return colorMap[product] || '#d9d9d9'; // 默认灰色
};

// 解析数组数据，处理字符串形式的数组
const parseArray = (data) => {
  if (!data) return [];
  if (Array.isArray(data)) return data;

  try {
    // 处理字符串形式的数组
    if (typeof data === 'string') {
      // 移除可能的括号
      const cleanStr = data.replace(/^\[/, '').replace(/\]$/, '').trim();
      if (!cleanStr) return [];

      // 分割并去除引号
      return cleanStr.split(',').map(item => {
        const trimmed = item.trim();
        // 去除可能的引号
        if ((trimmed.startsWith('"') && trimmed.endsWith('"')) ||
          (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
          return trimmed.slice(1, -1);
        }
        return trimmed === 'null' ? null : trimmed;
      });
    }
  } catch (error) {
    console.error('解析数组失败:', error);
  }

  return [data]; // 无法解析时返回单元素数组
};

// 解析嵌套数组（针对挂丝车等特殊情况）
const parseNestedArray = (data) => {
  if (!data) return [];

  try {
    let parsedData = data;

    // 如果是字符串，尝试解析为JSON
    if (typeof data === 'string') {
      parsedData = JSON.parse(data);
    }

    // 扁平化嵌套数组
    if (Array.isArray(parsedData)) {
      return parsedData.flatMap(item =>
        Array.isArray(item) ? item : [item]
      ).filter(item => item !== null && item !== undefined);
    }
  } catch (error) {
    console.error('解析嵌套数组失败:', error);
  }

  return parseArray(data); // 回退到普通解析
};

const productdata = ref({})

// WebSocket连接
let websocket = null;

// 初始化WebSocket连接
const initWebSocket = () => {
  // 如果已经存在连接，先关闭
  if (websocket) {
    websocket.close();
  }

  // 创建新的WebSocket连接
  websocket = new WebSocket(API_URLS.luosi.websocket);

  // 连接成功时触发
  websocket.onopen = () => {
    console.log("WebSocket连接已建立");
  };

  // 接收消息时触发
  websocket.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      productdata.value = data;
      console.log("通过WebSocket获取产品数据成功:", productdata.value);
    } catch (error) {
      console.error("解析WebSocket消息失败:", error);
    }
  };

  // 连接错误时触发
  websocket.onerror = (error) => {
    console.error("WebSocket连接错误:", error);
  };

  // 连接关闭时触发
  websocket.onclose = () => {
    console.log("WebSocket连接已关闭");
    // 尝试重新连接
    setTimeout(initWebSocket, 3000);
  };
};

// 通过WebSocket发送消息
const sendWebSocketMessage = (type) => {
  if (websocket && websocket.readyState === WebSocket.OPEN) {
    websocket.send(JSON.stringify({ type }));
  } else {
    console.error("WebSocket连接未建立");
  }
};

const getProductData = async () => {
  // 通过WebSocket请求最新状态
  sendWebSocketMessage("get_status");
};

const initSimulation = async () => {
  // 通过WebSocket发送初始化请求
  sendWebSocketMessage("init");
};

const startSimulation = async () => {
  // 通过WebSocket发送启动请求
  sendWebSocketMessage("start");
};

const stopSimulation = async () => {
  // 通过WebSocket发送停止请求
  sendWebSocketMessage("stop");
};

// 不再需要定时器，因为WebSocket会实时推送数据
const simulateAgvMovement = () => {
  // WebSocket会自动推送数据，不需要定时获取
  return null;
};

// 生命周期钩子
onMounted(() => {
  // 初始化WebSocket连接
  initWebSocket();
});

onUnmounted(() => {
  // 关闭WebSocket连接
  if (websocket) {
    websocket.close();
  }
});

// 监听数据变化
watch(productdata, (newVal, oldVal) => {
  console.log('productdata changed:', newVal);
}, { deep: true });
</script>
